import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:image_picker/image_picker.dart';
import 'package:talk/api/AlarmApi.dart';
import 'package:video_player/video_player.dart';
import 'package:talk/pages/device/x_device_router.dart';
import 'package:talk/tools/widgets/my_app_bar.dart';

import '../../api/DeviceApi.dart';
import '../../commponets/DropDownDevicePicker.dart';
import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../utils/toast_utils.dart';
import '../sip/call/sip_call.dart';
import 'model/Device.dart';
import 'dart:ui' as ui;
import 'dart:io';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';

class DeviceDetailsPage extends StatefulWidget {
  const DeviceDetailsPage({
    super.key,
    this.deviceId,
    this.type,
    this.sum, // 视频区域数量
    this.isScan = false,
    this.isSipInitialized,
    this.isRegistered,
  });

  final int? deviceId;
  final int? type;
  final int? sum; // 视频区域数量
  final bool isScan;
  final bool? isSipInitialized;
  final bool? isRegistered;

  @override
  State<DeviceDetailsPage> createState() => _DeviceDetailsPageState();
}

class _DeviceDetailsPageState extends State<DeviceDetailsPage> {
  late int _type;
  late String _statusText;
  late Color _statusColor;
  late int _videoCount; // 实际显示的视频数量
  final double _videoAreaHeight = 200.0; // 固定视频区域高度
  int? deviceType; // 设备类型
  late int _deviceId;
  Device? _device;
  late Future<Device?> _deviceFuture;

  late bool _isSipInitialized;
  late bool _isRegistered;
  String _localDeviceModel = "RM-1-1-1-1-1-1";
  String _callDeviceModel = "";
  String _deviceName = "";

  // 视频控制器
  late VideoPlayerController _videoController;
  bool _isVideoInitialized = false;
  // 定时器用于更新视频时间
  late Timer _timer;

  var actionKey = GlobalKey();
  final DeviceApi _deviceApi = DeviceApi();
  final AlarmApi _alarmApi = AlarmApi();

  String _selectedAlarmText = "Quad view";

  final ImagePicker _imagePicker = ImagePicker();
  final GlobalKey _screenshotKey = GlobalKey(); // 截屏区域标记

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId!;
    _isSipInitialized = widget.isSipInitialized!;
    _isRegistered = widget.isRegistered!;

    _type = widget.type ?? 1;
    _statusText = _type == 1 ? AppLocale.text('d_zaixian') : AppLocale.text('d_lixian');
    _statusColor = _type == 1 ?  Colors.green : Colors.grey;
    deviceType = null;

    // 初始化视频控制器 - 使用网络视频
    _initializeVideoPlayer();

    _deviceFuture = _fetchData();

    // 初始化定时器，每秒更新一次UI以刷新时间显示
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_isVideoInitialized && _videoController.value.isPlaying) {
        setState(() {}); // 触发UI刷新
      }
    });
  }

  // 初始化视频播放器 - 使用网络视频
  Future<void> _initializeVideoPlayer() async {
    // 使用网络视频URL替代本地资产
    // _videoController = VideoPlayerController.networkUrl(
    //   Uri.parse('http://43.139.39.5:82/pho/face/a.mp4'),
    //   // 允许缓存视频以提高播放体验
    //   videoPlayerOptions: VideoPlayerOptions(
    //     mixWithOthers: false,
    //   ),
    // );


    // // 加载本地assets中的视频文件
    _videoController = VideoPlayerController.asset(
      'images/images/video/a.mp4',
    );


    // 监听视频初始化完成
    _videoController.addListener(() {
      if (_videoController.value.isInitialized && !_isVideoInitialized) {
        setState(() {
          _isVideoInitialized = true;
        });
      }

      // 监听播放错误
      if (_videoController.value.hasError) {
        Toast.show(AppLocale.text('d_shipinbofangcuowu') + 
            " ${_videoController.value.errorDescription ?? AppLocale.text('d_weizhicuowu')}");
      }
    });

    try {
      // 初始化视频并设置循环播放
      await _videoController.initialize();
      _videoController.setLooping(true);
      await _videoController.play();
    } catch (e) {
      Toast.show(AppLocale.text('d_shipinchuhsihaushibai'));
      print("视频初始化错误: $e");
    }
  }

  Future<Device?> _fetchData() async {
    try {
      final response = await _deviceApi.getDeviceInfo(_deviceId);
      if (response.code == 200) {
        final device = Device.fromJson(response.data);
        // 确保视频数量在1-4之间
        _videoCount = (device.multiple ?? 1).clamp(1, 4);

        _callDeviceModel = device.deviceModel!;

        setState(() {
          _deviceName = device.deviceName!;
        });

        return device;
      } else {
        Toast.show(AppLocale.text('d_huoquyonghuyichang'));
        return null;
      }
    } catch (e) {
      Toast.show(AppLocale.text('d_jiazaishibai') + "${e.toString()}");
      return null;
    }
  }

  // 全屏播放视频
  void _playFullScreen() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => Scaffold(
          backgroundColor: Colors.black,
          body: Center(
            child: AspectRatio(
              aspectRatio: _videoController.value.aspectRatio,
              child: VideoPlayer(_videoController),
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              setState(() {
                _videoController.value.isPlaying
                    ? _videoController.pause()
                    : _videoController.play();
              });
            },
            child: Icon(
              _videoController.value.isPlaying ? Icons.pause : Icons.play_arrow,
            ),
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    // 释放资源
    _videoController.dispose();
    _timer.cancel(); // 取消定时器
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: _deviceName ?? '设备名称',
        backgroundColor: Colors.white,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
        buttonAlignment: MainAxisAlignment.end,
        contentAlignment: TextAlign.right,
      ),
      body: FutureBuilder<Device?>(
        future: _deviceFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Colors.blue),
              ),
            );
          }

          if (snapshot.hasError || snapshot.data == null) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    AppLocale.text('d_jiazaishujushibai'),
                    style: TextStyle(color: Colors.grey, fontSize: 16),
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton(
                    onPressed: () => setState(() {}),
                    child: Text(AppLocale.text('d_chongshi')),
                  ),
                ],
              ),
            );
          }

          _device = snapshot.data;
          return Column(
            children: [
              // 状态行
              Container(
                width: double.infinity,
                padding: const EdgeInsets.symmetric(vertical: 10),
                color: Colors.white,
                child: Row(
                  children: [
                    const SizedBox(width: 150),

                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        CircleAvatar(radius: 6, backgroundColor: _statusColor),
                        const SizedBox(width: 8),
                        Text(
                          _statusText,
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                            color: _statusColor,
                          ),
                        ),
                      ],
                    ),
                    const Spacer(),
                    Align(
                      alignment: Alignment.centerRight,
                      child: DropDownDevicePicker(
                        title: _selectedAlarmText,
                        titleStyle: const TextStyle(
                          fontSize: 14.0,
                          color: Colors.black,
                        ),
                        arrowIcon: const Icon(
                          Icons.sync_alt,
                          size: 20,
                          color: Colors.black87,
                        ),
                        deviceList: const [
                          'Quad view',
                          '通道0',
                          '通道1',
                          '通道2',
                          '通道3',
                          '通道4',
                        ],
                        itemStyle: const TextStyle(
                          fontSize: 14.0,
                          color: Color(0xFF595959),
                          fontWeight: FontWeight.bold,
                        ),
                        dropdownBackgroundColor: Colors.white,
                        mainContainerColor: Colors.transparent,
                        borderColor: Colors.transparent,
                        checkIcon: const Icon(
                          Icons.check,
                          color: Colors.black38,
                        ),
                        width: 140,
                        height: 50,
                        alignment: DropDownMainAxisAlignment.spaceEvenly,
                        dropdownWidth: 130,
                        maxDropdownHeight: 245,
                        trianglePosition: 85,
                        itemPadding: const EdgeInsets.only(left: 2.0),
                        onSelected: (device) {
                          print("设备类型选中了: $device");
                          setState(() {
                            _selectedAlarmText = device;
                          });

                          switch (device) {
                            case 'Quad view':
                              deviceType = 0;
                              break;
                            case '通道0':
                              deviceType = 1;
                              break;
                            case '通道1':
                              deviceType = 2;
                              break;
                            case '通道2':
                              deviceType = 3;
                              break;
                            case '通道3':
                              deviceType = 4;
                              break;
                            case '通道4':
                              deviceType = 5;
                              break;
                            default:
                              deviceType = null;
                          }
                        },
                        isSelected: (device) => device == _selectedAlarmText,
                      ),
                    ),
                  ],
                ),
              ),
              // 固定高度的视频区域
              Container(
                height: _videoAreaHeight,
                color: Colors.white,
                child: _buildVideoGrid(),
              ),
              // 功能按钮栏
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
                color: Colors.white,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _buildActionButton(Icons.crop_rotate, AppLocale.text('d_fangda'), onTap: _handleZoom),
                    _buildActionButton(Icons.crop, AppLocale.text('d_jieping'), onTap: _handleScreenshot),
                    _buildActionButton(
                      Icons.mic,
                      AppLocale.text('d_duijiang'),
                      onTap: _handleIntercom,
                      iconColor: _isSipInitialized && _isRegistered ? Colors.blue : Colors.black,
                    ),
                    _buildActionButton(Icons.fiber_manual_record, AppLocale.text('d_luping'),
                        iconColor: Colors.red, onTap: _handleRecord),
                    _buildActionButton(
                        Icons.settings,
                        AppLocale.text('d_shezhi'),
                        onTap: (){
                          _handleSettings(_deviceId, _type, _deviceName);
                        }
                    ),
                  ],
                ),
              ),
              // 开锁按钮
              Expanded(
                flex: 1,
                child: Center(
                  child: InkWell(
                    onTap: (){
                      _handleUnlock(_deviceId);
                    },
                    borderRadius: BorderRadius.circular(60),
                    child: Container(
                      width: 120,
                      height: 120,
                      decoration: BoxDecoration(
                        color: Colors.white,
                        borderRadius: BorderRadius.circular(60),
                        boxShadow: const [
                          BoxShadow(
                            color: Colors.grey,
                            blurRadius: 10,
                            spreadRadius: 2,
                          ),
                        ],
                      ),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          const Icon(Icons.lock, color: Colors.blue, size: 40),
                          const SizedBox(height: 8),
                          Text(
                            AppLocale.text('d_kaisuo'),
                            style: TextStyle(
                              color: Colors.blue,
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),
            ],
          );
        },
      ),
    );
  }

  // 视频区域（带截屏标记）
  Widget _buildVideoGrid() {
    return RepaintBoundary(
      key: _screenshotKey,
      child: Container(
        height: _videoAreaHeight,
        color: Colors.white,
        child: switch (_videoCount) {
          1 => _buildSingleVideo(),
          2 => _buildTwoVideos(),
          3 => _buildThreeVideos(),
          _ => _buildFourVideos(),
        },
      ),
    );
  }

  // 构建单个视频区域，播放网络视频
  Widget _buildSingleVideo() {
    return Container(
      color: Colors.grey[300],
      child: Stack(
        children: [
          // 视频播放器
          if (_isVideoInitialized)
            AspectRatio(
              aspectRatio: _videoController.value.aspectRatio,
              child: VideoPlayer(_videoController),
            )
          else if (_videoController.value.hasError)
            Center(
              child: Text(
                AppLocale.text('d_shipinjiazaishibai'),
                style: TextStyle(color: Colors.red),
              ),
            )
          else
            const Center(child: CircularProgressIndicator()),

          // 播放/暂停控制按钮
          Positioned.fill(
            child: GestureDetector(
              onTap: () {
                setState(() {
                  _videoController.value.isPlaying
                      ? _videoController.pause()
                      : _videoController.play();
                });
              },
              child: Container(
                color: Colors.transparent,
                child: Center(
                  child: Icon(
                    _videoController.value.isPlaying
                        ? Icons.pause
                        : Icons.play_arrow,
                    color: Colors.white54,
                    size: 48,
                  ),
                ),
              ),
            ),
          ),

          // 视频时间显示
          Positioned(
            top: 4,
            left: 4,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
              color: Colors.black54,
              child: Text(
                _formatDuration(_videoController.value.position),
                style: const TextStyle(color: Colors.white, fontSize: 12),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 辅助方法：格式化视频时长
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final hours = twoDigits(duration.inHours);
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return [if (duration.inHours > 0) hours, minutes, seconds].join(':');
  }

  // 构建两个视频区域
  Widget _buildTwoVideos() {
    return Row(
      children: [
        Expanded(child: _buildVideoItem(0)),
        Expanded(child: _buildVideoItem(1)),
      ],
    );
  }

  // 构建三个视频区域
  Widget _buildThreeVideos() {
    return Column(
      children: [
        Expanded(child: _buildVideoItem(0)),
        Expanded(
          child: Row(
            children: [
              Expanded(child: _buildVideoItem(1)),
              Expanded(child: _buildVideoItem(2)),
            ],
          ),
        ),
      ],
    );
  }

  // 构建四个视频区域
  Widget _buildFourVideos() {
    return Column(
      children: [
        Expanded(
          child: Row(
            children: [
              Expanded(child: _buildVideoItem(0)),
              Expanded(child: _buildVideoItem(1)),
            ],
          ),
        ),
        Expanded(
          child: Row(
            children: [
              Expanded(child: _buildVideoItem(2)),
              Expanded(child: _buildVideoItem(3)),
            ],
          ),
        ),
      ],
    );
  }

  // 构建单个视频项
  Widget _buildVideoItem(int index) {
    return Container(
      child: Stack(
        children: [
          Positioned(
            top: 4,
            left: 4,
            child: Container(
              padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 2),
            ),
          ),
          Positioned.fill(
            child: Material(
              color: Colors.transparent,
              child: InkWell(
                child: const Center(
                  child: Icon(Icons.add, color: Colors.grey),
                ),
                onTap: () => _handleVideoItemTap(index),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 构建功能按钮
  Widget _buildActionButton(IconData icon, String text,
      {Color? iconColor, VoidCallback? onTap}) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(8),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(icon, color: iconColor ?? Colors.black, size: 24),
          const SizedBox(height: 4),
          Text(text, style: const TextStyle(fontSize: 12)),
        ],
      ),
    );
  }

  void _handleIntercom() async{
    print('执行对讲操作');
    SipCall.makeCall(context, username: _callDeviceModel);
    Toast.show(AppLocale.text('d_zhengzaihujiao')  + _callDeviceModel);


    //发送消息
    final toUpdate = {
      "callName": _callDeviceModel,
      "callType": 0,
    };
    _deviceApi.callMessage(toUpdate);
  }




  Future<void> _handleScreenshot() async {
    Toast.show(AppLocale.text('d_zhengzaibaochunjietu'));

    try {
      if (_screenshotKey.currentContext == null) {
        Toast.show(AppLocale.text('d_jiepinquyuweizhunbeihao'));
        return;
      }

      RenderRepaintBoundary boundary =
      _screenshotKey.currentContext!.findRenderObject() as RenderRepaintBoundary;

      await Future.delayed(const Duration(milliseconds: 200));

      ui.Image image = await boundary.toImage(pixelRatio: 3.0);
      ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
      if (byteData == null) {
        Toast.show(AppLocale.text('d_wufahuoqutuxiangshuju'));
        return;
      }

      Uint8List pngBytes = byteData.buffer.asUint8List();
      if (pngBytes.isEmpty) {
        Toast.show(AppLocale.text('d_jiepinshujuweikong'));
        return;
      }

      String? savePath;
      if (Platform.isAndroid) {
        savePath = '/storage/emulated/0/Pictures/MyAppScreenshots/';
        Directory(savePath).createSync(recursive: true);
      } else if (Platform.isIOS) {
        final directory = await getApplicationDocumentsDirectory();
        savePath = directory.path;
      } else {
        Toast.show(AppLocale.text('d_buzhidchipingtai'));
        return;
      }

      String fileName = 'screenshot_${DateTime.now().millisecondsSinceEpoch}.png';
      String fullPath = '$savePath$fileName';
      File file = File(fullPath);
      await file.writeAsBytes(pngBytes);
      print("截图已保存到：$fullPath");

      if (await file.exists()) {
        print("文件保存成功，大小：${await file.length()} bytes");
      } else {
        Toast.show(AppLocale.text('d_wenjianbaochunweihbai'));
        return;
      }

      if (Platform.isAndroid) {
        const platform = MethodChannel('com.example.talk/update_gallery');
        try {
          await platform.invokeMethod('insertImage', {
            'filePath': fullPath,
            'title': fileName,
            'description': 'Screenshot from MyApp'
          });
          Toast.show(AppLocale.text('d_jietubaochunchenggongdata'));
        } catch (e) {
          print("更新媒体库失败: $e");
          try {
            await _imagePicker.pickImage(source: ImageSource.gallery);
            Toast.show(AppLocale.text('d_jietubaochunchenggongdata'));
          } catch (e) {
            Toast.show(AppLocale.text('d_jietubaochunchenggonggexxin'));
          }
        }
      } else {
        Toast.show(AppLocale.text('d_jietubaochunchenggong'));
      }

    } catch (e) {
      print("截屏失败: $e");
      Toast.show(AppLocale.text('d_jietubaochunshibai'));
    }
  }

  void _handleSettings(int deviceId, int type, String deviceName) {
    final encodedDeviceName = Uri.encodeComponent(deviceName);
    NavigatorUtils.push(context, '${XDeviceRouter.deviceSettingPage}'
        '?deviceId=$deviceId&type=$type&deviceName=$encodedDeviceName');
  }

  // 放大按钮点击事件，触发全屏播放
  void _handleZoom() => _playFullScreen();

  void _handleRecord() => print('执行录屏操作');

  void _handleUnlock(int deviceId){
    print('执行开锁操作');

    final toUpdate = {
      "deviceId": _device?.deviceId,
      "openDoor": 1,
    };
    _deviceApi.openDoor(toUpdate);

    Toast.show(AppLocale.text('d_kaisuoxinxiyifasong'));
  }

  void _handleVideoItemTap(int index) => print('点击了视频项 $index');
}
